package com.yuexiang.melodyhub.gateway.filter.security;

import com.yuexiang.melodyhub.common.constant.UsualConstant.PathConstant;
import com.yuexiang.melodyhub.common.utils.VerificationUtil;
import com.yuexiang.melodyhub.gateway.component.AuthProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.regex.Pattern;

@Component
public class CheckAnonymousPathProcessor extends AuthProcessor {

    private final AuthProperties properties;

    @Autowired
    public CheckAnonymousPathProcessor(AuthProperties properties) {
        this.properties = properties;
    }

    @Override
    public Mono<Void> process(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().value();
        if (isAnonymous(path)) return chain.filter(exchange);
        return next.process(exchange, chain);
    }

    private boolean isAnonymous(String path) {
        List<String> authorizedPath = properties.getRoles().get(PathConstant.ANONYMOUS);
        return authorizedPath != null && authorizedPath.stream().anyMatch(authP -> Pattern.compile(VerificationUtil.convertToRex(authP)).matcher(path).matches());
    }

}
